<template>
  <view class="viewport">
    <!-- tabs -->
    <view class="tabs">
      <text class="item" v-for="item,index in orderTabs" :key="index" @tap="changeTab(index)"> {{ item.title }} </text>
      <!-- 游标 -->
      <view class="cursor" :style="{ left: activeIndex * 20 + '%' }"></view>
    </view>
    <!-- 滑动容器 -->
    <swiper class="swiper" :current="activeIndex" @change="swiper_change">
      <!-- 滑动项 -->
      <swiper-item v-for="item,index in orderTabs" :key="index">
        <!-- 订单列表 -->
        <scroll-view scroll-y class="orders" @scrolltolower="onScrolltolower">
          <view class="card" v-for="item,index in orderList?.items" :key="index">
            <!-- 订单信息 -->
            <view class="status">
              <text class="date">{{ item.createTime }}</text>
              <!-- 订单状态文字 -->
              <text>{{ orderState_str(item.orderState) }}</text>
              <!-- 待评价/已完成/已取消 状态: 展示删除订单 -->
              <text class="icon-delete" v-if="item.orderState == 4 || item.orderState == 5 || item.orderState == 6" @tap="del_order(item.id)"></text>
            </view>
            <!-- 商品信息，点击商品跳转到订单详情，不是商品详情 -->
            <navigator v-for="sku,i in item?.skus" :key="i" class="goods" :url="`/orderPages/orderDetail/orderDetail?orderId=${item.id}`" hover-class="none">
              <view class="cover">
                <image mode="aspectFit" :src="sku.image"></image>
              </view>
              <view class="meta">
                <view class="name ellipsis">{{ sku.name }}</view>
                <view class="type">{{ sku.attrsText }}</view>
              </view>
            </navigator>
            <!-- 支付信息 -->
            <view class="payment">
              <text class="quantity">共{{ item.totalNum }}件商品</text>
              <text>实付</text>
              <text class="amount"> <text class="symbol">¥</text>{{ item.payMoney }}</text>
            </view>
            <!-- 订单操作按钮 -->
            <view class="action">
              <!-- 待付款状态：显示去支付按钮 -->
              <template v-if="item.orderState == 1">
                <view class="button primary" @tap="order_payment_btn(item.id)">去支付</view>
              </template>
              <template v-else>
                <navigator class="button secondary" :url="`/pages/goods/goods?id=${item.skus[0].spuId}`" hover-class="none">再次购买</navigator>
                <!-- 待收货状态: 展示确认收货 -->
                <view v-if="item.orderState == 3" class="button primary" @tap="order_confirm_btn(item.id)">确认收货</view>
              </template>
            </view>
          </view>
          <!-- 底部提示文字 -->
          <view class="loading-text" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
            {{ orderList.page < orderList.pages || orderList.pages == 0 ? '没有更多数据~' : '正在加载...' }}
          </view>
        </scroll-view>
      </swiper-item>
    </swiper>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue';
import { onLoad, onShow } from "@dcloudio/uni-app";
//引入请求函数
import { reqOrderList, reqDeleteOrder, reqWxPayParams, reqPayMock, reqOrderReceipt } from "@/services/order.ts";

//获取页面参数
const props = defineProps<{
    type:number|string
}>();

//当前活动索引
let activeIndex:number = ref();

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
// tabs 数据
const orderTabs = ref([
  { orderState: 0, title: '全部' },
  { orderState: 1, title: '待付款' },
  { orderState: 2, title: '待发货' },
  { orderState: 3, title: '待收货' },
  { orderState: 4, title: '待评价' },
]);
//请求订单列表数据参数
let orderParams = reactive({
  page:1,
  pageSize:5,
  type:0,
  pages:0  //服务器返回总页数
})
//uni-生命周期
onLoad(()=>{
  //初始赋值
  if(props.type){
    activeIndex.value = Number(props.type);
  }
});
//侦听器，监听当前活动索引
watch(activeIndex,(newVal,oldVal)=>{
  //侦听索引加载不同type订单数据
  orderParams.type = newVal;
  orderParams.page = 1;
  orderList.items = [];  //置空，加载不同type类型的订单
  getOrderList();  //重新请求数据
},{ immediate: false })

//订单列表数据
let orderList = reactive({
  counts:0,
  pageSize:0,  //每页多少条数
  page:0,
  pages:0,  //服务器返回总页数
  items:[]
});


//swiper的change事件
const swiper_change = ($event:any) => {
  activeIndex.value = $event.detail.current;  //修改活动索引
}
//tabs的点击事件，修改当前活动索引
const changeTab = (i:number) => {
  activeIndex.value = i;
}
//获取订单列表数据
const getOrderList = async () => {
  //展示loadding提示框
  uni.showLoading({title:"加载中...",mask:true});
  //发请求
  let res = await reqOrderList(orderParams.page,orderParams.pageSize,orderParams.type);
  orderList.count = res.result.count;
  orderList.pageSize = res.result.pageSize;
  orderList.pages = res.result.pages;
  orderParams.pages = res.result.pages;
  //初次请求数据还是加载更多订单数据
  if(orderList.item?.length == 0){
    orderList.items = res.result.items;
  } else {
    orderList.items.push(...res.result.items);
  } 
  console.log("订单列表数据api",res);
  //关闭loadding提示框
  uni.hideLoading();
}
//将订单状态数字标识--->文本
const orderState_str = (state:number) => {
  let str = "";
  if(state == 1){
    str = "待付款";
  } else if (state == 2) {
    str = "待发货";
  } else if (state == 3) {
    str = "待收货";
  } else if (state == 4) {
    str = "待评价";
  } else if (state == 5) {
    str = "已完成";
  } else if (state == 6) {
    str = "已取消";
  }
  return str;
}
//滚动条的下拉触底事件
const onScrolltolower = () => {
  //加载更多订单
  if(orderParams.page >= orderParams.pages) return;
  orderParams.page ++;
  //发请求
  getOrderList();
}
//订单操作按钮:此处不重新发订单列表请求
//付款
const order_payment_btn = async (orderId:string) => {
  //进行支付
  if(import.meta.env.DEV){
    //开发环境
    let res = await reqPayMock(orderId);
    uni.showToast({icon:"success",title:"模拟支付成功"});
    console.log('模拟支付api',res);
  } else {
    //生产环境
    let res = await reqWxPayParams(orderId);
    console.log("获取微信支付参数api",res);
    wx.requestPayment(res.result);  //调用微信支付
  }
  //本地对该笔订单状态修改
  orderList.items.forEach(element => {
    if(element.id == orderId){
      element.orderState = 2;
    }
  });
}
//确认收货
const order_confirm_btn = (orderId:string) => {
  //二次确认弹窗
  uni.showModal({
    content:"为保障您的权益，请收到货并确认无误后，在确认收货",
    success:async (success)=>{
      if(success.confirm){
        //发请求
        let res = await reqOrderReceipt(orderId);
        //本地更新订单状态
        orderList.items.forEach(element => {
          if(element.id == orderId){
            element.orderState = 4;
          }
        });
      }
    },
  })
}
//删除
const del_order = async (orderId:string) => {
  let res = await reqDeleteOrder([orderId]);
  console.log('订单删除api',res);
  //直接本地修改订单列表数据
  orderList.items = orderList.items.filter(item =>{
    return item.id != orderId;
  })
}

</script>

<style lang="scss">
page {
  height: 100%;
  overflow: hidden;
}

.viewport {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #fff;
}

// tabs
.tabs {
  display: flex;
  justify-content: space-around;
  line-height: 60rpx;
  margin: 0 10rpx;
  background-color: #fff;
  box-shadow: 0 4rpx 6rpx rgba(240, 240, 240, 0.6);
  position: relative;
  z-index: 9;

  .item {
    flex: 1;
    text-align: center;
    padding: 20rpx;
    font-size: 28rpx;
    color: #262626;
  }

  .cursor {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 20%;
    height: 6rpx;
    padding: 0 50rpx;
    background-color: #27ba9b;
    /* 过渡效果 */
    transition: all 0.4s;
  }
}

// swiper
.swiper {
  background-color: #f7f7f8;
}

// 订单列表
.orders {
  .card {
    min-height: 100rpx;
    padding: 20rpx;
    margin: 20rpx 20rpx 0;
    border-radius: 10rpx;
    background-color: #fff;

    &:last-child {
      padding-bottom: 40rpx;
    }
  }

  .status {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 28rpx;
    color: #999;
    margin-bottom: 15rpx;

    .date {
      color: #666;
      flex: 1;
    }

    .primary {
      color: #ff9240;
    }

    .icon-delete {
      line-height: 1;
      margin-left: 10rpx;
      padding-left: 10rpx;
      border-left: 1rpx solid #e3e3e3;
    }
  }

  .goods {
    display: flex;
    margin-bottom: 20rpx;

    .cover {
      width: 170rpx;
      height: 170rpx;
      margin-right: 20rpx;
      border-radius: 10rpx;
      overflow: hidden;
      position: relative;
    }

    .quantity {
      position: absolute;
      bottom: 0;
      right: 0;
      line-height: 1;
      padding: 6rpx 4rpx 6rpx 8rpx;
      font-size: 24rpx;
      color: #fff;
      border-radius: 10rpx 0 0 0;
      background-color: rgba(0, 0, 0, 0.6);
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
    }

    .name {
      height: 80rpx;
      font-size: 26rpx;
      color: #444;
    }

    .type {
      line-height: 1.8;
      padding: 0 15rpx;
      margin-top: 10rpx;
      font-size: 24rpx;
      align-self: flex-start;
      border-radius: 4rpx;
      color: #888;
      background-color: #f7f7f8;
    }

    .more {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 22rpx;
      color: #333;
    }
  }

  .payment {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    line-height: 1;
    padding: 20rpx 0;
    text-align: right;
    color: #999;
    font-size: 28rpx;
    border-bottom: 1rpx solid #eee;

    .quantity {
      font-size: 24rpx;
      margin-right: 16rpx;
    }

    .amount {
      color: #444;
      margin-left: 6rpx;
    }

    .symbol {
      font-size: 20rpx;
    }
  }

  .action {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding-top: 20rpx;

    .button {
      width: 180rpx;
      height: 60rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-left: 20rpx;
      border-radius: 60rpx;
      border: 1rpx solid #ccc;
      font-size: 26rpx;
      color: #444;
    }

    .secondary {
      color: #27ba9b;
      border-color: #27ba9b;
    }

    .primary {
      color: #fff;
      background-color: #27ba9b;
    }
  }

  .loading-text {
    text-align: center;
    font-size: 28rpx;
    color: #666;
    padding: 20rpx 0;
  }
}   
</style>